<template>
  <el-card>
    <el-tabs v-model="activeName">
      <el-tab-pane label="角色管理" name="first">
        <el-button type="primary" @click="add">新增角色</el-button>
        <el-table :data="rows" border style="margin-top:20px">
          <el-table-column label="序号" type="index" width="100px" align="center">
            <template #default="{$index}">
              {{ (params.page-1)*params.pagesize + $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="success" size="small" @click="showPermission(row)">分配权限</el-button>
              <el-button type="primary" size="small" @click="edit(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="del(row.id)"
              >
                <el-button slot="reference" type="danger" size="small" style="margin-left:6px">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align:center;margin-top:20px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="params.pagesize"
            @current-change="changePage"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="公司信息" name="second">
        <el-alert
          title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
          type="info"
          show-icon
          :closable="false"
        />
        <el-form label-width="120px" style="margin-top:50px">
          <el-form-item label="公司名称">
            <el-input :value="companyInfo.name" disabled style="width:400px" />
          </el-form-item>
          <el-form-item label="公司地址">
            <el-input :value="companyInfo.companyAddress" disabled style="width:400px" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input :value="companyInfo.mailbox" disabled style="width:400px" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input :value="companyInfo.remarks" type="textarea" :rows="3" disabled style="width:400px" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      @close="reset"
    >
      <el-form ref="roleRef" label-width="100px" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="display:block;text-align:center">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="为角色分配权限"
      :visible.sync="permissionVisible"
      width="30%"
    >
      <el-tree ref="tree" :data="permissionList" :props="{label:'name'}" default-expand-all show-checkbox node-key="id" :default-checked-keys="checkedPermissionList" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="permissionVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePermission">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { getCompanyInfo, getRoleList, addRole, updateRole, deleteRole } from '@/api/setting'
import { getPermissionList, getPermissionByRoleId, assignPerm } from '@/api/permisson'
import { tranListToTreeData } from '@/utils/index'
export default {
  data() {
    return {
      activeName: 'first',
      companyInfo: {},
      params: {
        page: 1,
        pagesize: 3
      },
      rows: [],
      total: null,
      dialogVisible: false,
      title: '',
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      permissionVisible: false,
      permissionList: [],
      checkedPermissionList: [],
      id: null
    }
  },
  created() {
    this.getCompanyInfo()
    this.getRoleList()
  },
  methods: {
    // 公司信息
    async getCompanyInfo() {
      const res = await getCompanyInfo(this.$store.getters.companyId)
      // console.log(res)
      this.companyInfo = res
    },
    // 角色列表渲染
    async getRoleList() {
      const res = await getRoleList(this.params)
      // console.log(res)
      this.rows = res.rows
      this.total = res.total
    },
    // 分页
    changePage(current) {
      this.params.page = current
      this.getRoleList()
    },
    // 弹窗
    add() {
      this.title = '新增角色'
      this.dialogVisible = true
    },
    // 重置表单
    reset() {
      this.$refs.roleRef.resetFields()
      this.roleForm = {}
    },
    // 点击确定触发事件
    async save() {
      try {
        // 二次校验
        await this.$refs.roleRef.validate()
        if (this.title === '新增角色') {
          // 新增角色
          await addRole(this.roleForm)
          this.$message.success('添加成功')
        } else {
          await updateRole(this.roleForm)
          this.$message.success('修改成功')
        }
        this.dialogVisible = false
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑角色事件
    edit(row) {
      this.title = '编辑角色'
      this.roleForm = { ...row }
      this.dialogVisible = true
    },
    // 删除角色事件
    async del(id) {
      try {
        await deleteRole(id)
        this.$message.success('删除成功')
        // 只有当前页面只有一条数据，并且不是第一页的时候就可以去上一页
        if (this.rows.length === 1 && this.params.page > 1) {
          this.params.page--
        }
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },

    // 分配权限弹窗
    async showPermission(row) {
      this.id = row.id
      console.log(row)
      // 根据角色的id获取权限列表
      const res1 = await getPermissionByRoleId(row.id)
      console.log(res1)
      // 传入data数组里,让子节点默认选中
      this.checkedPermissionList = res1.permIds
      // 获取权限接口
      const res = await getPermissionList()
      // console.log(res)
      // 引入树形结构并传入data里的空数组
      this.permissionList = tranListToTreeData(res, '0')
      console.log(this.permissionList)
      this.permissionVisible = true
    },

    // 给角色分配权限
    async savePermission() {
      // console.log(this.$refs.tree.getCheckedKeys())
      await assignPerm({ id: this.id, permIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success('更新成功')
      this.permissionVisible = false
    }
  }
}
</script>

<style scoped lang='scss'></style>
